# -*- coding:utf-8 -*-
# __author__ : "张百科"
# Date: 2021/1/22 14:00
# File: user.py
# IDE: PyCharm
from rest_framework import serializers
from django.contrib.auth.models import User
from django.conf import settings
from models.user import User
from rest_framework.validators import UniqueValidator, ValidationError
from django.contrib.auth.hashers import make_password
class UserSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    token = serializers.CharField(read_only=True)
    user_name=serializers.CharField(label='姓名')
    last_login_time=serializers.SerializerMethodField()  # 自定义显示
    login_count=serializers.IntegerField(label='登录次数')
    email = serializers.CharField(label='邮箱')
    duty=serializers.CharField(label='职务')
    remark=serializers.CharField(label='备注')
    outtime = serializers.SerializerMethodField()
    class Meta:
        model = User
        fields = ('id','token','user_name','last_login_time','outtime','login_count','email','duty','remark')

    def get_last_login_time(self, row):
        return row.last_login_time.strftime('%Y-%m-%d %H:%M:%S')
    def get_outtime(self, row):
        return    settings.TOKEN_OUT_TIME

class UserDetailSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    user_name = serializers.CharField(label='姓名', required=True,read_only=False)

    login_name = serializers.CharField(label='登录工号', max_length=100, min_length=4, help_text='登录工号',
                                 validators=[
                                     UniqueValidator(
                                         queryset=User.objects.all(),
                                         message='该工号已存在'
                                     )
                                 ],
                                 error_messages={
                                     ## 键值对，对应上面的限制条件，以及对应的提示
                                     'max_length': '最长100个字符',
                                     'min_length': '最短4个字符'
                                 }
                                 )
    mobile = serializers.CharField(label='联系电话', max_length=11, min_length=8, help_text='联系电话', required=True,
                                error_messages={
                                    'max_length': '最长11个字符',
                                    'min_length': '最短8个字符'
                                })
    email = serializers.CharField(label='邮箱', max_length=50, min_length=2, help_text='邮箱', required=False,
                                  error_messages={
                                      'max_length': '最长500个字符',
                                      'min_length': '最短2个字符'
                                  })
    dep_id = serializers.IntegerField(read_only=True)
    avator = serializers.CharField(label='头像url', help_text='头像url', required=False)
    duty = serializers.CharField(label='职务', help_text='职务', required=False)
    remark = serializers.CharField(label='备注', max_length=500, help_text='备注', allow_blank=True,
                                   required=False,
                                   error_messages={
                                       'max_length': '最长500个字符'
                                   })
    login_count = serializers.IntegerField(label='登录次数', read_only=True, help_text='对接原因')
    is_delete = serializers.IntegerField(read_only=True, required=False, help_text='系统状态（1 启用 0 禁用）')
    is_allowed_login = serializers.IntegerField(read_only=True, required=False, help_text='是否允许（1 允许 0 禁止）')

    last_login_time = serializers.SerializerMethodField(read_only=True)
    class Meta:
        model = User
        exclude = ('password',)

    def get_last_login_time(self, row):
        return row.last_login_time.strftime('%Y-%m-%d %H:%M:%S')

    def create(self, validated_data):
        # some actions

        validated_data['password'] = make_password(validated_data['mobile'])
        instance = super().create(validated_data)
        return instance

    def update(self, instance, validated_data):
        # 更新的特别之处在于你已经获取到了这个对象instance
        instance.user_name = validated_data.get('user_name')
        instance.mobile = validated_data.get('mobile')
        instance.avator=validated_data.get('avator')
        instance.duty = validated_data.get('duty')
        instance.remark=validated_data.get('remark')
        instance.email = validated_data.get('email')
        instance.save()
        return instance



